package com.kuang.service.impl;

import com.alibaba.fastjson.JSON;
import com.kuang.pojo.Content;
import com.kuang.service.ContentService;
import com.kuang.utils.ESConst;
import com.kuang.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: kuangshen-es-api
 * @description:
 * @author: 陈恩涛
 * @create: 2021-05-27 10:40
 **/

@Service
public class ContentServiceImpl implements ContentService {

    @Resource(name = "restHighLevelClient")
    private RestHighLevelClient client;

    @Autowired
    private HtmlParseUtil htmlParseUtil;

    @Override
    public Boolean parseContent(String keyword) throws IOException {
        List<Content> contents = htmlParseUtil.parseJD(keyword);
        //批量插入到ES中
        BulkRequest request = new BulkRequest();
        request.timeout("2m");
        for (int i = 0; i < contents.size(); i++) {
            request.add(
                    new IndexRequest("jd_goods")
                            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        return !responses.hasFailures();
    }

    //2、获取这些数据，实现搜索功能
    @Override
    public List<Map<String, Object>> searchPage(String keyword, int pageNum, int pageSize) throws IOException {
        if (pageNum <= 1) {
            pageNum = 1;
        }

        //条件搜索
        SearchRequest request = new SearchRequest(ESConst.JD_GOODS_INDEX);

        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //查询构造器，我们可以使用QueryBuilders工具来实现
        //termQuery精确匹配
        //matchALLQuery 匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        builder.query(termQueryBuilder);

        //分页
        builder.from((pageNum - 1) * pageSize);
        builder.size(pageSize);

        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : response.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }

        return list;
    }

    @Override
    public List<Map<String, Object>> searchPageHighlight(String keyword, int pageNum, int pageSize) throws IOException {

        if (pageNum <= 1) {
            pageNum = 1;
        }

        //条件搜索
        SearchRequest request = new SearchRequest(ESConst.JD_GOODS_INDEX);

        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //查询构造器，我们可以使用QueryBuilders工具来实现
        //termQuery精确匹配
        //matchALLQuery 匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        builder.query(termQueryBuilder);

        //分页
        builder.from((pageNum - 1) * pageSize);
        builder.size(pageSize);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title")//传入要高亮哪一个字段，并且高亮几个字
                .preTags("<span style='color:red'>")  //传入前缀
                .postTags("</span>")//传入后缀
                .requireFieldMatch(true);  //如果要多个字段高亮,这项要为false
        builder.highlighter(highlightBuilder);

        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : response.getHits().getHits()) {
            HighlightField title = documentFields.getHighlightFields().get("title");
            //原来的结果
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            //解析高亮的字段，将原来的字段置换为高亮的字段即可
            if (title != null) {
                Text[] fragments = title.fragments();
                StringBuilder highlightTitle = new StringBuilder();
                for (Text text : fragments) {
                    highlightTitle.append(text);
                }
                sourceAsMap.put("title",highlightTitle.toString());
            }
            list.add(sourceAsMap);
        }
        return list;
    }

}
